package com.woniuxy.handler;

import java.io.IOException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.woniuxy.pojo.User;
import com.woniuxy.pojo.User1;
import com.woniuxy.service.UserService;
import lombok.Data;

@Controller
@RequestMapping("/user")
@Scope("prototype")
@Data
public class UserHandler {
    @Resource
    public UserService userService;

	@RequestMapping("/login")
    public String login(User1 user, HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {

		System.out.println(user);
        // 1 获取subject对象
        Subject currentUser = SecurityUtils.getSubject();
        // 2,判断当前用户是否认证过了
        if (!currentUser.isAuthenticated()) {
            // 3,进行验证
            /*
             * 1.执行currentUser.login(token)方法时会调用securityManager中的 login()方法，
             * 
             * 同时将token传递过去
             * 
             * 2.securityManager会根据shiro配置文件中的配置信息
             * 
             * 自动的调用 自定义realm的doGetAuthenticationInfo()方法，获取账号信息
             * 
             * 3.如果该方法返回值是null，直接抛出UnknownAccountException异常
             * 
             * 否则该方法将查询到的账号密码返回给securityManager
             * 
             * 4.securityManager根据返回的结果比较密码是否一致
             * 
             * 如果不一致抛出IncorrectCredentialsException异常 如果一致，代表认证成功
             */

            // 加密输入的账号进行匹配--使用代码加密才使用以下代码，配置文件方式的加密不需要写
            /*
             * String salt = user.getAccount(); String newPwd = new SimpleHash("MD5", user.getPwd(),
             * salt, 1024).toString(); user.setPwd(newPwd);
             */


            UsernamePasswordToken token =
                    new UsernamePasswordToken(user.getAccount(), user.getPwd());
            try {
                currentUser.login(token);// 进行验证
                System.out.println("验证成功");
                return "/jsp/main.jsp";
            } catch (UnknownAccountException e) {
                request.setAttribute("message", "没有这个账号");
                request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
                // throw new CustomException("用户名不能为空");
                System.out.println("没有这个账号");

            } catch (IncorrectCredentialsException e) {
                request.setAttribute("message", "密码错误");
                request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);

                System.out.println("密码错误");

            } catch (LockedAccountException e) {

                request.setAttribute("message", "账号被锁定");
                request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
                System.out.println("账号被锁定");

            } catch (AuthenticationException e) {

                request.setAttribute("message", "身份验证异常");
                request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
                System.out.println("身份验证异常");

            }

        }

        return "/jsp/main.jsp";
	}

    @RequestMapping("/register")
    public String register(User user) {
        System.out.println("前端的数据：" + user);
        String oldPwd = user.getUser_password();
        //佐料
        String salt = user.getUser_phone();
        // 加密
        String newPwd = new SimpleHash("MD5", oldPwd, salt, 1024).toString();

        user.setUser_password(newPwd);
        System.out.println("加密后的密码：" + user.getUser_password());
        int number = userService.addUser(user);
        if (number == 0) {
            System.out.println("注册失败");
            return "/register.html";
        }
        System.out.println("账号是：" + number);
        return "/index.html";

    }

}
